package cc.vv.btpartyjob.partymanager.view

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.text.Editable
import android.text.TextUtils
import android.text.TextWatcher
import android.util.AttributeSet
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import cc.vv.baselibrary.util.LKDialogUtil
import cc.vv.baselibrary.util.LKTimeUtil
import cc.vv.baselibrary.vFinal.BTKey
import cc.vv.baselibrary.view.pickerview.adapter.ArrayWheelAdapter
import cc.vv.baselibrary.view.pickerview.lib.WheelView
import cc.vv.baselibrary.view.util.DateChoseDialog
import cc.vv.btpartyjob.partymanager.R
import cc.vv.btpartyjob.partymanager.inter.CleanAddProjectItemClickInterface
import cc.vv.btpartyjob.partymanager.moudel.bean.AddProjectObj
import cc.vv.lkbasecomponent.util.LKScreenUtil
import cc.vv.lklibrary.log.LogOperate
import java.text.SimpleDateFormat
import java.util.*

/**
 * 添加项目阶段
 * Created by  Chen.qi on 2018/10/24.
 */
class AddProjectView : LinearLayout {
    /**
     * 上下文
     */
    private var mContext: Context? = null
    /**
     * 父布局
     */
    private var llSelectedAll: LinearLayout? = null

    /**
     * 集合状态数据
     */
    private val strList = listOf("未开始", "进行中", "已完成")


    constructor(context: Context) : this(context, null) {
        mContext = context
    }

    constructor(context: Context, attrs: AttributeSet?) : this(context, attrs, 0) {
        mContext = context
    }

    constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {
        mContext = context
        val inflateView = View.inflate(context, R.layout.layout_operation_view, null)
        llSelectedAll = inflateView.findViewById(R.id.ll_lov_showAll)
        this.addView(inflateView)
    }


    /**
     * 填充选项数据
     *
     * @param optionList 数据集
     * @param itemSize   每行有几个选项
     */
    @SuppressLint("SetTextI18n")
    fun addAllSelectedFileView(optionList: ArrayList<AddProjectObj>?, cleanInter: CleanAddProjectItemClickInterface) {
        if (null == optionList) {
            return
        }
        //清除
        clearAllJobOptionView()
        val viewWight = (LKScreenUtil.getScreenWidth() - LKScreenUtil.dp2px(48f))
        val layoutParams1 = LayoutParams(viewWight, LayoutParams.WRAP_CONTENT)
        for (i in 0 until optionList!!.size) {
            val view = LayoutInflater.from(mContext).inflate(R.layout.layout_add_project_stage_other, null)
            view.layoutParams = layoutParams1
            view.setPadding(LKScreenUtil.dp2px(12f), 0, 0, 0)
            val etContent = view.findViewById<TextView>(R.id.et_stage_proContent_other)
            val cleanOther = view.findViewById<ImageView>(R.id.iv_stage_clean_other)
            val tvStage = view.findViewById<TextView>(R.id.tv_stage_title_other)

            val llyJTime = view.findViewById<LinearLayout>(R.id.ll_stage_addStartTime_other)
            val tvyJtime = view.findViewById<TextView>(R.id.tv_stage_yuJinTime_other)


            val llEndTime = view.findViewById<LinearLayout>(R.id.ll_stage_endtime_other)
            val tvEndtime = view.findViewById<TextView>(R.id.tv_stage_completeTime_other)

            val llState = view.findViewById<LinearLayout>(R.id.ll_stage_addState_other)
            val tvState = view.findViewById<TextView>(R.id.tv_stage_projectState_other)

            tvStage?.text = "第${i + 1}阶段"
            val addProjectObj = optionList[i]
            etContent?.text = addProjectObj.content

            if (null != addProjectObj.warningTime) {
                if (addProjectObj.warningTime!! > 0) {
                    val formatTime = LKTimeUtil.getInstance().formatTime("yyyy-MM-dd", addProjectObj.warningTime!!)
                    tvyJtime?.text = formatTime
                }
            }
            if (null != addProjectObj.completeTime) {
                if (addProjectObj.completeTime!! > 0) {
                    val formatTime = LKTimeUtil.getInstance().formatTime("yyyy-MM-dd", addProjectObj.completeTime!!)
                    tvEndtime?.text = formatTime
                }
            }
            if (null != addProjectObj.state) {
                when (addProjectObj.state) {
                    0 -> {
                        tvState?.text = "未开始"
                    }
                    1 -> {
                        tvState?.text = "进行中"
                    }
                    2 -> {
                        tvState?.text = "已完成"
                    }
                }
            }

            etContent.addTextChangedListener(object : TextWatcher {
                override fun afterTextChanged(s: Editable?) {
                    cleanInter?.changeContent(i, s?.toString())
                }

                override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

                }

                override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {

                }

            })

            cleanOther.setOnClickListener({
                cleanInter?.cleanItem(i)
            })

            llyJTime?.setOnClickListener({
                chooseStartData(mContext!!, i, cleanInter, tvyJtime, 0)
            })

            llEndTime?.setOnClickListener({
                chooseStartData(mContext!!, i, cleanInter, tvEndtime, 1)
            })
            llState?.setOnClickListener({
                getWheelerWayDialog(i, mContext as Activity, "选择方式", strList, cleanInter, tvState)
            })

            llSelectedAll?.addView(view)
        }
    }

    /**
     * 清除view
     */

    private fun clearAllJobOptionView() {
        llSelectedAll?.removeAllViews()
    }


    /**
     * 选择预警时间
     */
    private fun chooseStartData(context: Context, pos: Int, cleanInter: CleanAddProjectItemClickInterface, tvTime: TextView, type: Int) {
        var birthday = ""
        val birthArr = birthday.split("-".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
        var year = Calendar.getInstance().get(Calendar.YEAR)
        var month = Calendar.getInstance().get(Calendar.MONTH)
        var day = Calendar.getInstance().get(Calendar.DAY_OF_MONTH)
        if (birthArr.size == BTKey.BTKEY_INT_3) {
            try {
                year = Integer.parseInt(birthArr[0])
                month = Integer.parseInt(birthArr[1]) - 1
                day = Integer.parseInt(birthArr[2])
            } catch (e: Exception) {
                LogOperate.e(e.message)
            }
        }
        //初始化显示控件
        DateChoseDialog.getInstance().initBirthDatePicker(context, year, month, day, 3)
        DateChoseDialog.getInstance().setBrithDatenterface { date ->
            val sdf = SimpleDateFormat("yyyy-MM-dd")
            val format = sdf.format(date)
            if (type == 0) {
                cleanInter?.changeYJtime(pos, format)
            } else if (type == 1) {
                cleanInter?.changeCompleteTime(pos, format)
            }
            tvTime?.text = format
        }
        DateChoseDialog.getInstance().showBirthDateDialog()
    }


    /**
     * 滚轮dialog
     */
    private fun getWheelerWayDialog(position: Int, activity: Activity, title: String, strList: List<String>, cleanInter: CleanAddProjectItemClickInterface?, tvState: TextView?) {

        val view = activity.layoutInflater.inflate(R.layout.layout_select_cancel_reason_dialog, null)
        val dialog = LKDialogUtil.getBottomDialog(activity, view)
        //取消
        val tvCancel = view.findViewById<TextView>(R.id.tv_lscrd_cancel)
        //确定
        val tvCommit = view.findViewById<TextView>(R.id.tv_lscrd_commit)
        //标题
        val tvTitle = view.findViewById<TextView>(R.id.tv_lscrd_title)
        tvTitle.text = title
        //滚动控件
        val wvWheel = view.findViewById<WheelView>(R.id.wv_lscrd_select_cancel_reason)

        val fontSize = 16f
        val lineSpacing = 2.5f
        val itemVisibleCount = 7
        var pos = 0

        wvWheel.setTextSize(fontSize)
        wvWheel.setCyclic(false)
        wvWheel.setLineSpacingMultiplier(lineSpacing)
        wvWheel.itemsVisible = itemVisibleCount
        wvWheel.adapter = ArrayWheelAdapter(strList, strList.size)
        wvWheel.setOnItemSelectedListener { index ->
            pos = index
        }
        tvCancel.setOnClickListener { dialog.dismiss() }

        tvCommit.setOnClickListener {
            val selStr = strList[pos]
            tvState?.text = selStr
            cleanInter?.changeProjectStatus(position, selStr)
            dialog.dismiss()
        }
        dialog.show()
    }


}